package top.yongyan0624.security;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.yongyan0624.Utils.GetRequestJsonUtils;
import top.yongyan0624.Utils.RedisUtil;
import top.yongyan0624.common.exception.CaptchaException;
import top.yongyan0624.common.lang.Const;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Yongyan
 * @description
 * @date 2021/5/12
 **/

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String uri = httpServletRequest.getRequestURI();
        // 只有当这个请求路径为 "/login"，并且为post请求，才被当做登录请求，来进行验证码校验
        if ("/login".equals(uri) && "POST".equals(httpServletRequest.getMethod())) {
            // 校验验证码
            try {
                validate(httpServletRequest);
            } catch (CaptchaException e) {
                //若验证码出错，交给认证失败处理器处理
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }

        }
        //非登录请求、或者登录请求验证成功后，放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    //校验验证码的逻辑
    private void validate(HttpServletRequest httpServletRequest) throws CaptchaException, IOException {
        //获取用户输入
        //因为 httpServletRequest.getParameter()无法解析json格式数据，无法取出里面的code值，所以使用工具类解析
        JSONObject jsonObject = GetRequestJsonUtils.getRequestJsonObject(httpServletRequest);
        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("token");
        if (code == null){
            code = jsonObject.getString("code");
        }
        if (key == null){
            key = jsonObject.getString("token");
        }

        if (StringUtils.isBlank(key) || StringUtils.isBlank(code)) {
            //输入为空，抛出异常
            throw new CaptchaException("验证码错误！");
        }

        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))) {
            //从redis中取出的code与用户输入的code不相等，抛出异常
            throw new CaptchaException("验证码错误！");
        }

        //验证码只能使用一次，所以认证成功要删除
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }
}
